<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style type="text/css">
        #box {
            width: 100px;
            height: 100px;
            background: #07d268;
            position: absolute;
            left: 100px;
            top: 100px;
        }
    </style>
</head>
<body>
<div id="box">1</div>
</body>
<script>
  const box = document.querySelector('#box');
  let drag = false;
  let position = [];
  box.addEventListener('mousedown', (e) => {
    drag = true
    position = [e.clientX, e.clientY]
  })
  document.addEventListener('mousemove', (e) => {
    if (drag !== true) {
      return
    }
    const x = e.clientX;
    const y = e.clientY;
    const left = parseInt(getComputedStyle(box).left || 0);    //js获取head里css需要用getComputedStyle
    const top = parseInt(getComputedStyle(box).top || 0);
    box.style.left = left + x - position[0] + 'px'
    box.style.top = top + y - position[1] + 'px'
    position = [x, y]
  })
  document.addEventListener('mouseup', () => {
    drag = false
  })
</script>
</html>
